<?php
/**
 * 使用迭代器最简单的方法是实现\Iterator的5个方法
 * 迭代器模式的使用场景：
 * 1.使用迭代器模式，你可以在不知道内部构造时使用foreach来进行循环
 */

namespace App\DesignPattern\Iterator;

use App\DesignPattern\Factory\OrmFactory;


class UserIterator implements \Iterator
{
    private $index = 0;

    private $users = [];

    public function __construct()
    {
        $orm = OrmFactory::createOrm();
        $this->users = $orm->query("SELECT * FROM `user`");
    }

    public function current()
    {
        return $this->users[$this->index];
    }

    public function key()
    {
        return $this->index;
    }

    public function next()
    {
        $this->index ++;
    }

    public function rewind()
    {
        $this->index = 0;
    }

    public function valid()
    {
        return isset($this->users[$this->index]);
    }
}